package com.github.fashionbrot;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TestBeanPostProcessor implements InitializingBean, DisposableBean, EnvironmentAware, Ordered {

    private Environment environment;

    private ScheduledExecutorService executorService;


    @Override
    public void destroy() throws Exception {
        log.info("TestBeanPostProcessor destroy...");
        executorService.shutdown();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Long listenLongPollMs = 5000L;
        executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setName("com.github.fashionbrot.spring.event.MarsTimerHttpBeanPostProcessor");
                t.setDaemon(true);
                return t;
            }
        });
        executorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                try{
                    SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println(sf.format(new Date()));
                }catch (Throwable e){
                    log.error("MarsTimerHttpBeanPostProcessor longPull error",e);
                }
            }
        },0,listenLongPollMs, TimeUnit.MILLISECONDS);
    }

    @Override
    public void setEnvironment(Environment environment) {
        environment = environment;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
